new Vue({
    el: '#app',
    mixins: [Query],//组件配置文件，路径/utils/components.js
    data() {
        return {
            form: {//查询筛选
                value: '',
                value2: '-', // 状态：'-'全部、'0'待审核、'2'已通过、'3'拒绝
                PageNumber: 1, //页码
                RowAmount: 20,
                // Condition 两参：关键词,状态
                Condition: utf8ToBase64(`%%,%%`),
            },
            enterpriseId: $.cookie('enterprise') || '',
            confirmContractDialogVisible: false,
            confirmContractRow: null,
            dialogSupplyInvoiceVisible: false,
            supplyInvoiceUploading: false,
            supplyInvoicePictureUrl: '',
            supplyInvoiceOrderRow: null,
        }
    },
    mounted() {
        /**
         * 组件配置文件中自动执行方法
         * 1.this.getColumn(); //查询表头数据
         * 2.this.getList(this.form); //查询表格数据
         * 3.this.getTreeData();//查询树
         */
    },
    methods: {
        // 卖方权限：仅当该订单属于当前企业时显示操作按钮
        canOperate(row) {
            const ent = (row && (row.Enterprise_Info_SerialNumber || row.Seller_Enterprise_SerialNumber)) || '';
            const cur = this.enterpriseId || $.cookie('enterprise') || '';
            return ent && cur && String(ent) === String(cur);
        },
        confirmContract(row) {
            try {
                // 优先传递当前订单号，合同详情将按订单号精确展示
                const orderSerial = row.Supply_Order_SerialNumber || row.Trading_Apply_SerialNumber || '';
                // 其次传递报价编号，合同详情将按报价编号筛选
                const supplyId = row.Supply_Unit_Price_SerialNumber || '';
                const url = orderSerial
                    ? `./contract_details.html?orderSerial=${encodeURIComponent(orderSerial)}`
                    : (supplyId
                        ? `./contract_details.html?supplyId=${encodeURIComponent(supplyId)}`
                        : './contract_details.html');
                window.location.href = url;
            } catch (e) {
                console.error(e);
                this.$message.error('系统错误，请联系开发者!');
            }
        },
        // 线上签约入口（可在此对接线上合同页面）
        startOnlineSigning(row) {
            try {
                this.confirmContractDialogVisible = false;
                this.$message.success('已选择：线上签约');
                // TODO: 在此发起线上签约流程或跳转到签约页面
                // 例如：window.location.href = '../../../view/InvitingTenders/AllNeeds/ConfirmContract.html'
            } catch (e) { console.error(e); this.$message.error('系统错误，请联系开发者!'); }
        },
        // 线下签约入口（可在此记录线下签约意向或跳转线下流程）
        startOfflineSigning(row) {
            try {
                this.confirmContractDialogVisible = false;
                this.$message.success('已选择：线下签约');
                // TODO: 在此记录线下签约意向或跳转到线下流程页面
            } catch (e) { console.error(e); this.$message.error('系统错误，请联系开发者!'); }
        },
        openSupplyInvoiceDialog(row) {
            try {
                this.supplyInvoiceOrderRow = row || null;
                this.supplyInvoicePictureUrl = '';
                this.dialogSupplyInvoiceVisible = true;
            } catch (e) { console.error(e); this.$message.error('系统错误，请联系开发者!'); }
        },
        async uploadSupplyInvoice(file) {
            try {
                const f = file && (file.raw || file);
                if (!f) return;
                const res = await generalApi.generalUploadStream(f);
                if (res && res.status === 'success') {
                    this.supplyInvoicePictureUrl = res.fileName;
                    this.$message.success('上传成功');
                } else {
                    this.$message.error('上传失败');
                }
            } catch (e) {
                console.error(e);
                this.$message.error('系统错误，请联系开发者!');
            }
        },
        async submitSupplyInvoice() {
            try {
                const row = this.supplyInvoiceOrderRow || {};
                const orderId = String(row.Supply_Order_SerialNumber || '');
                if (!orderId) { this.$message.error('未找到订单编号'); return; }
                if (!this.supplyInvoicePictureUrl) { this.$message.warning('请先上传发票图片'); return; }
                this.supplyInvoiceUploading = true;
                const now = getYMDHMSDate();
                const addRow = [{
                    Supply_Order_Invoice_SerialNumber: '',
                    Supply_Order_SerialNumber: orderId,
                    Supply_Order_Paystages_SerialNumber: '',
                    Picture_URL: String(this.supplyInvoicePictureUrl),
                    Enterprise_Info_SerialNumber: getCookie('enterprise') || '',
                    Creater_SerialNumber: getCookie('user') || '',
                    Create_Datetime: now,
                    Operation_ID: getCookie('user') || '',
                    Operation_Datetime: now,
                    Row_Status: '0'
                }];
                const lJSONObject_DataSet = { Add: { supply_order_invoice: addRow } };
                const Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                lJSONObject_DataSet['Add']['base_operation_log'] = [{
                    Operation_Type: '0', Operation_Path: getRelativePath(),
                    Operation_Description: '上传供应订单发票', Operation_Main,
                    Operation_Interface: 'generalSaveByRequestBody', Operation_IP: getIpAddress()
                }];
                const res = await generalApi.generalSaveByRequestBody({ Data: lJSONObject_DataSet });
                this.supplyInvoiceUploading = false;
                if (res && res.Status === 'success') {
                    this.$message.success('提交成功');
                    this.dialogSupplyInvoiceVisible = false;
                    this.getList(this.form);
                } else {
                    this.$message.error('提交失败，请重试');
                }
            } catch (e) {
                console.error(e);
                this.supplyInvoiceUploading = false;
                this.$message.error('系统错误，请联系开发者!');
            }
        },
        handleSerach() { //筛选
            const val = this.form.value2;
            const status = (val === '-' || val === '' || val == null) ? '%%' : val;
            this.form.PageNumber = 1;
            this.form.Condition = utf8ToBase64(`%${this.form.value}%,${status}`);
            this.getList(this.form);
        },
        // 状态切换：更新 Condition 第二参数并刷新列表
        handleTabsClick() {
            const val = this.form.value2;
            const status = (val === '-' || val === '' || val == null) ? '%%' : val;
            this.form.PageNumber = 1;
            this.form.Condition = utf8ToBase64(`%${this.form.value}%,${status}`);
            this.getList(this.form);
        },
       
        handleShow(row) { // 查看购买记录（按申请流水号筛选）
            try {
                const { primaryKey } = $('#table').data('options');
                const applyId = row.Supply_Order_SerialNumber || row.Trading_Apply_SerialNumber || row[primaryKey];
                if (!applyId) {
                    this.$message({ message: '未获取到申请流水号', type: 'error' });
                    return;
                }
                window.location.href = `../supply_order/details.html?applyId=${encodeURIComponent(applyId)}&fromPage=sales_order`;
            } catch (error) {
                console.error(error);
                this.$message({
                    message: '系统错误，请联系开发者!',
                    type: 'error'
                })
            }
        },
       
    }
})
